from flask import Flask, request, jsonify, render_template_string
import requests
import json
import os

app = Flask(__name__)

# HTML 模板和样式，嵌入到 Python 文件中
html_template = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chatbot Interface</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 80%;
            margin: 0 auto;
            padding: 20px;
            background-color: white;
            margin-top: 50px;
            box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            text-align: center;
            color: #333;
        }
        .chat-box {
            background-color: #fafafa;
            border: 1px solid #ddd;
            padding: 10px;
            height: 300px;
            overflow-y: scroll;
            margin-bottom: 20px;
        }
        .user-message, .bot-message {
            margin: 10px 0;
            padding: 10px;
            border-radius: 5px;
        }
        .user-message {
            background-color: #d1ecf1;
            text-align: right;
        }
        .bot-message {
            background-color: #f8d7da;
            text-align: left;
        }
        .input-area {
            display: flex;
        }
        .input-area input[type="text"] {
            flex-grow: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .input-area button {
            padding: 10px 20px;
            border: none;
            background-color: #007bff;
            color: white;
            cursor: pointer;
            border-radius: 5px;
            margin-left: 10px;
        }
        .input-area button:hover {
            background-color: #0056b3;
        }
        .file-upload {
            margin-top: 10px;
            display: flex;
            align-items: center;
        }
        .file-upload input {
            padding: 5px;
        }
        .file-upload button {
            margin-left: 10px;
            padding: 8px 15px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Chat with Bot</h1>
        <div class="chat-box" id="chat-box">
            <!-- Chat messages will appear here -->
        </div>
        <div class="input-area">
            <input type="text" id="user-input" placeholder="Type your message here">
            <button onclick="sendMessage()">Send</button>
        </div>
        <div class="file-upload">
            <input type="file" id="file-input">
            <button onclick="uploadFile()">Upload Image</button>
        </div>
    </div>

    <script>
        function sendMessage() {
            const userInput = document.getElementById("user-input").value;
            if (userInput === '') return;

            // Add user message to chat box
            const chatBox = document.getElementById("chat-box");
            const userMessage = document.createElement("div");
            userMessage.classList.add("user-message");
            userMessage.textContent = userInput;
            chatBox.appendChild(userMessage);

            // Send user message to server
            fetch('/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ message: userInput })
            })
            .then(response => response.json())
            .then(data => {
                // Add bot message to chat box
                const botMessage = document.createElement("div");
                botMessage.classList.add("bot-message");
                botMessage.textContent = data.answer;
                chatBox.appendChild(botMessage);

                // Clear the input field
                document.getElementById("user-input").value = '';

                // Scroll to the bottom of the chat
                chatBox.scrollTop = chatBox.scrollHeight;
            });
        }

        function uploadFile() {
            const fileInput = document.getElementById('file-input');
            const file = fileInput.files[0];
            if (!file) return;

            const formData = new FormData();
            formData.append('file', file);

            // Upload file to server
            fetch('/upload', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.id) {
                    alert('File uploaded successfully with ID: ' + data.id);
                } else {
                    alert('File upload failed.');
                }
            });
        }
    </script>
</body>
</html>
"""

# 上传文件到百度千帆
def upload_image_to_qianfan(file):
    url = "https://qianfan.baidubce.com/v2/app/conversation/file/upload"
    
    payload = {
        'app_id': 'a3ce3c1b-5ec8-4475-8d27-ec4fc51fada5'
    }
    files = [
        ('file', (file.filename, file.stream, file.mimetype))
    ]
    headers = {
        'X-Appbuilder-Authorization': 'Bearer bce-v3/ALTAK-0xAsDlbnUXSFk6hJQuQTs/15230c6d9bfd153624c38736c50eb9194d7eb7a1'
    }

    response = requests.post(url, headers=headers, data=payload, files=files)
    response_json = response.json()
    return response_json.get("id")

# 跟百度千帆API交互的函数
def get_bot_response(user_input, file_id=None):
    url = "https://qianfan.baidubce.com/v2/app/conversation/runs"
    
    payload = {
        "app_id": "a3ce3c1b-5ec8-4475-8d27-ec4fc51fada5",
        "query": user_input,
        "stream": False,
    }

    if file_id:
        payload["file_ids"] = [file_id]

    headers = {
        'Content-Type': 'application/json',
        'X-Appbuilder-Authorization': 'Bearer bce-v3/ALTAK-0xAsDlbnUXSFk6hJQuQTs/15230c6d9bfd153624c38736c50eb9194d7eb7a1'
    }

    response = requests.post(url, headers=headers, json=payload)
    response_json = response.json()
    
    # 提取answer字段
    return response_json.get("answer", "Sorry, I couldn't understand your message.")

# 首页路由，渲染前端页面
@app.route('/')
def index():
    return render_template_string(html_template)

# 处理聊天请求的路由
@app.route('/chat', methods=['POST'])
def chat():
    user_input = request.json.get('message')
    bot_response = get_bot_response(user_input)
    return jsonify({"answer": bot_response})

# 处理图片上传请求的路由
@app.route('/upload', methods=['POST'])
def upload():
    if 'file' not in request.files:
        return jsonify({"error": "No file part"}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400

    # 上传文件到百度千帆
    file_id = upload_image_to_qianfan(file)
    if file_id:
        return jsonify({"id": file_id})
    else:
        return jsonify({"error": "Failed to upload file"}), 500

if __name__ == '__main__':
    app.run(debug=True)
